package service

import (
	"context"
	"github.com/coreos/etcd/clientv3"
	"gitee.com/man0sions/go-cron/common"
	"log"
	"time"
)

type Register struct {
	client  *clientv3.Client
	kv      clientv3.KV
	lease   clientv3.Lease
	localIp string
}

var GRegister *Register

func (register *Register) keepOnline() {
	var (
		err    error
		gres   *clientv3.LeaseGrantResponse
		kresCh <-chan *clientv3.LeaseKeepAliveResponse
		cancel context.CancelFunc
		ctx    context.Context
	)
	for {
		key := common.ETCD_WORKER_DIR + register.localIp
		if gres, err = register.lease.Grant(context.TODO(), 10); err != nil {
			goto RETRY
		}
		if kresCh, err = register.lease.KeepAlive(context.TODO(), gres.ID); err != nil {
			goto RETRY
		}
		ctx, cancel = context.WithCancel(context.TODO())
		if _, err = register.kv.Put(ctx, key, "", clientv3.WithLease(gres.ID)); err != nil {
			goto RETRY
		}
		for {
			select {
			case r := <-kresCh:
				if r == nil {
					common.Warn(nil, "续租失败")
					goto RETRY
				}

			}
		}
	RETRY:
		log.Println("retry...", err)
		time.Sleep(time.Second * 10)
		if cancel != nil {
			cancel()
		}
	}
}

func InitRegister() (err error) {
	localIp, _ := common.GetIp()
	GRegister := &Register{
		client:  common.GEtcd.Client,
		kv:      common.GEtcd.Kv,
		lease:   common.GEtcd.Lease,
		localIp: localIp,
	}
	go GRegister.keepOnline()
	return
}
